package com.darren.euc.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.darren.euc.dao.*;
import com.darren.euc.entity.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.darren.euc.service.ClueService;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;


@Service
public class ClueServiceImpl implements ClueService {
	
	private static final Logger log = Logger.getLogger(ClueServiceImpl.class);
	
	@Autowired
    private ClueDao clueDao;

	@Autowired
    private ClueFollowDao clueFollowDao;

	@Autowired
	private SpaceDao spaceDao;
	
	@Autowired
    private ClueRemarkDao clueRemarkDao;
	
	@Autowired
    private ClientDao clientDao;
	
    @Override
    public Clue save(Clue clue) {
    	if(clue != null && clue.getClient() !=null){
    		if(clue.getClient().getId() != null){
    			clientDao.update(clue.getClient());
    		}else{
    			clientDao.save(clue.getClient());
    		}
    	}
        return clueDao.save(clue);
    }
    
    @Override
    public ClueFollow saveClueFollow(ClueFollow clueFollow){
        return clueFollowDao.save(clueFollow);
    }
    
    @Override
    public ClueRemark saveClueRemark(ClueRemark clueRemark){
        return clueRemarkDao.save(clueRemark);
    }

    @Override
    public Clue update(Clue clue) {
    	if(clue != null && clue.getClient() !=null){
    		if(clue.getClient().getId() != null){
    			clientDao.update(clue.getClient());
    		}else{
    			clientDao.save(clue.getClient());
    		}
    	}
        return clueDao.update(clue);
    }
    
    @Override
    public Clue findById(Integer id) {
        return clueDao.findById(id);
    }

    @Override
    public Clue delete(Clue clue) {
    	clue = clueDao.findById(clue.getId());
    	if(clue != null){
    		clue.setEnable(false);
    		clueDao.update(clue);
    	}
    	//clueDao.delete(clue);
    	return clue;
    }
    
	@Override
	public List<Clue> getAll() {
		return clueDao.getAll();
	}
	
	
	@SuppressWarnings("rawtypes")
	public PageBean queryForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){		
		String HQL = null;
		String likes = null;
		String equals = null;
		List<Object> parameters = new ArrayList<Object>();
		JSONObject likeJson = requestJson.getJSONObject("like");
		Iterator likeIterator = likeJson.keys();
		while(likeIterator.hasNext()){
			String key = (String) likeIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = likeJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				likes = (likes == null?"": likes + " OR ") +  key + " like ? ";
				parameters.add("%"+value+"%");
			}
		}
		HQL = likes == null?null:(" (" + likes + ") ");		
		JSONObject equalsJson = requestJson.getJSONObject("equals");
        Iterator equalsIterator = equalsJson.keys();        
		while(equalsIterator.hasNext()){
			String key = (String) equalsIterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = equalsJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				if("visitTimeStart".equals(key)){
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
					try {
						Date startDate = (Date)format.parse(value);
						parameters.add(startDate);
					} catch (ParseException e) {
						log.error(e.getMessage(),e);
					} 
					equals = (equals == null?"": ""+equals + " and ") +  " visitTime >= ? ";					
				}else if("visitTimeEnd".equals(key)){
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
					try {
						Date endDate = (Date)format.parse(value);
						Calendar calendar = Calendar.getInstance(); 
						calendar.setTime(endDate); 						
						int day=calendar.get(Calendar.DATE); 
						calendar.set(Calendar.DATE,day+1); 				
						parameters.add(calendar.getTime());
					} catch (ParseException e) {
						log.error(e.getMessage(),e);
					} 
					equals = (equals == null?"": ""+equals + " and ") +  " visitTime <= ? ";
					
				}else if("spaceId".equals(key)){
					equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
					parameters.add(Integer.parseInt(value));
				}else if("enable".equals(key)){
					equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
					parameters.add(Boolean.parseBoolean(value));
				}else{
					equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
					parameters.add(value);
				}				
			}
		}		
		if(HQL != null){
			if(equals != null){
				HQL = HQL + " and " + equals;
			}
		}else{
			HQL = equals;
		}
		HQL = " from Clue where enable = true  and processPerson is null" + (HQL == null?"":" and  " + HQL) + "  order by createTime desc ";
		return clueDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
	}

	@Override
	public Clue saveReserve(Clue clue) {
		Space space = spaceDao.findById(clue.getSpaceId());
		if (space != null){
			clue.setProvinceId(space.getProvince().getProvinceId());
			clue.setCityId(space.getCity().getCityId());
		}

		clueDao.save(clue);
		return clue;
	}


}